package com.umbrella.security;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

public class RSA {

	final static String transformation = "RSA/ECB/PKCS1Padding";
	public static Map<String, RSAKey> getKey() throws NoSuchAlgorithmException {

		KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
		keyGenerator.initialize(1024);
		KeyPair keyPair = keyGenerator.generateKeyPair();
		RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
		RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
		System.out.println("privateKey:" + Base64.getEncoder().encodeToString(privateKey.getEncoded()));
		System.out.println("publicKey:" + Base64.getEncoder().encodeToString(publicKey.getEncoded()));
		Map<String, RSAKey> keys = new HashMap<String, RSAKey>();
		keys.put("private", privateKey);
		keys.put("public", publicKey);
		return keys;
	}

	public static String encrypt(String data, RSAPublicKey publicKey) throws Exception {
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		byte[] result = cipher.doFinal(data.getBytes("UTF-8"));
		String encrypt = Base64.getEncoder().encodeToString(result);
		return encrypt;
	}

	public static String decrypt(String data, RSAPrivateKey privateKey) throws Exception {
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		byte[] result = cipher.doFinal(Base64.getDecoder().decode(data));
		return new String(result, "UTF-8");
	}
}
